$m(function (args) {
    var $this = $(this.element).closest("body");
    var controller = new MinePublishServiceController(analyse_id);
    controller.serviceDialog = $('.app-task-config-container');
    controller.service = {};
    controller.service.id = row.id;
    controller.service.themeId = analyse_id;
    var job = null;
    var id = args.id;
    var a = resPar;
    var b = resParam;
    var firstJobStatus = null;
    //编辑状态
    var editStatus = {
        all: false,
        serviceInfo: false,
        envInfo: false,
        limit: false,
        flowParams: false
    };

    //国际化
    var locale = TempoUtils.locale;

    //执行模式
    var EXCUTE_MODE = {
        "SYNC_ON_LOCAL": '本地',
        "SYNC_ON_YARN": '集群',
        "本地": "SYNC_ON_LOCAL",
        "集群": "SYNC_ON_YARN"
    };

    //环境参数
    var $env = $this.find(".env-info");
    var envTable = $env.find('.env-info-table');

    //资源使用情况
    var $resource = $this.find(".resource-info");
    var resourceGrid = $resource.find(".app-task-config-resource-info-form");

    //python资源限制
    var $limitInfo = $this.find(".limit-info");
    var limitGrid = $limitInfo.find('#tempo-mine-flow-limit-info');

    //流程参数
    var $paramInfo = $this.find(".flowparam-info");
    var paramGrid = $paramInfo.find('#flowparam-info-table');

    //请求参数
    var $requestInfo = $this.find(".request-info");
    var requestGrid = $requestInfo.find('#request-info-table');

    //相应参数
    var $responseInfo = $this.find(".response-info");
    var responseGrid = $responseInfo.find('#response-info-table');

    /**
     *  加载上次修改的流程参数
     */
    var loadFlowsParam = function () {
        var totalParam = resParam.flowsParam[args.serviceId];
        var flowParamsArray = totalParam.filter(function (v) {
            if (v.paramType !== "configResources") {
                return true;
            }
        });
        var params = {};

        if (resParam && resParam.flowsParam && resParam.flowsParam[args.serviceId]) {
            var resParams = resParam.flowsParam[args.serviceId];
            var obj = {};
            for (var i = 0; i < resParams.length; i++) {
                var param = resParams[i];
                var paramType = param["paramType"];
                var paramValue = param["paramValue"];
                if ("configResources" == paramType) {
                    var paramName = param["paramName"];
                    if ("driverCpu" == paramName) {
                        obj["cpu"] = paramValue;
                    } else if ("driverMemory" == paramName) {
                        obj["mem"] = paramValue;
                    } else if ("totalExecutorCores" == paramName) {
                        obj["execcpu"] = paramValue;
                    } else if ("exeProcessNum" == paramName) {
                        obj["executors"] = paramValue;
                    } else if ("executorMemory" == paramName) {
                        obj["execmemory"] = paramValue;
                    } else if ("cacheType" == paramName) {
                        obj["cacheconfig"] = paramValue;
                    } else if ("gpu" == paramName) {
                        obj["gpu"] = paramValue;
                    } else if ("limitExtendCpu" == paramName) {
                        obj["limitCpu"] = paramValue;
                    } else if ("limitExtendMemory" == paramName) {
                        obj["limitMemory"] = paramValue;
                    } else if ("" == paramName || "mode" == paramName) {
                        //判断执行模式为空，兼容历史不可删除
                        obj["mode"] = paramValue;
                    }
                }
            }
            if (!$.isEmptyObject(obj)) {
                var currentParam = resPar.filter(function (v) {
                    if (v.$configResources$ != null) {
                        return true
                    }
                })[0];
                var configResources = JSON.parse(currentParam.$configResources$);
                if (configResources.gpu && !obj.gpu) {
                    obj["gpu"] = configResources.gpu || 0;
                } else if (!configResources.gpu && obj.gpu) {
                    delete obj["gpu"]
                }
                params = {"$configResources$": JSON.stringify(obj)};
            } else {
                params = resPar.filter(function (v) {
                    if (v.$configResources$ != null) {
                        return true
                    }
                })[0];
            }
        }
        flowParamsArray.push(params);
        return flowParamsArray;
    }

    window.resPar = (resParam.flowsParam == undefined) ? resPar : loadFlowsParam();

    //流程参数
    var flowArray = resPar.filter(function (v) {
        if (v === null) {
            return false;
        }
        if (v.paramName === "system.appId") {
            return false;
        } else if (v.$configResources$ == null) {
            return true;
        }
    });

    var dataSourceCache = {};

    var buildOperHtml = function () {
        var operhtml = '<div class="tempo-task-button"><button id="tempo-task--param-save' + id + '" style="height:26px;line-height:26px;" class="tempo-button ui-button">保存</button></div>';
        //operhtml += '<div class="tempo-task-button tempo-task-detail-button" id="tempo-task-stop'+id+'"><span class="tempo-api-icon-18 tempo-api-icon-18-position-task-stop tempo-task-detail-btn-icon tempo-task-stop-btn" id="tempo-task-stop-btn'+id+'"></span><span class="tempo-task-stop-label" id="tempo-task-stop-label'+id+'">停止任务</span></div>';
        operhtml += '<div class="tempo-task-button tempo-task-detail-button" id="tempo-task-pause' + id + '"><span class="tempo-api-icon-18 tempo-api-icon-18-position-task-pause tempo-task-detail-btn-icon tempo-task-pause-or-start-btn" id="tempo-task-pause-or-start-btn' + id + '"></span><span class="tempo-task-pause-or-start" id="tempo-task-pause-or-start' + id + '">暂停任务</span></div>';
        operhtml += '<div class="tempo-task-button tempo-task-detail-button" id="tempo-task-manual' + id + '"><span class="tempo-api-icon-18 tempo-api-icon-18-position-task-manual tempo-task-detail-btn-icon tempo-task-manual-btn" id="tempo-task-manual-btn' + id + '"></span><span class="tempo-task-manual-label" id="tempo-task-manual-label' + id + '">手动执行</span></div>';
        return operhtml;
    }

    /**
     * 构建周页面
     */
    var buildWeeks = function (dialog) {
        var board = dialog.find('.times-board');
        var weeks = [2, 3, 4, 5, 6, 7, 1];
        var weekName = [TempoUtils.locale("mine.xinqiyi"),
            TempoUtils.locale("mine.xinqier"),
            TempoUtils.locale("mine.xinqisan"),
            TempoUtils.locale("mine.xinqisi"),
            TempoUtils.locale("mine.xinqiwu"),
            TempoUtils.locale("mine.xinqiliu"),
            TempoUtils.locale("mine.xinqitian")
        ];
        weeks.forEach(function (e, i) {
            var span = $("<span style='display: inline-block;width: 100px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofweek' type='checkbox'/>").val(e).appendTo(span);
            $("<label/>").text(weekName[i]).appendTo(span);
        });
        TempoUtils.parserUi(board, {});
    };

    /**
     * 构建天页面
     */
    var buildDays = function (dialog) {
        var board = dialog.find('.times-board');
        for (var i = 1; i <= 31; i++) {
            var span = $("<span style='display: inline-block;width: 100px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
                .val(i)
                .addClass('day-of-month-' + i)
                .appendTo(span);
            $("<label/>").text(i + TempoUtils.locale("mine.hao")).appendTo(span);
        }
        var lastSpan = $("<span style='display: inline-block;width: 100px;'></span>").appendTo(board);
        $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
            .val("L")
            .addClass('day-of-month-L')
            .appendTo(lastSpan);
        $("<label/>").text(TempoUtils.locale("mine.zuihouyitian")).appendTo(lastSpan);
        TempoUtils.parserUi(board, {});
    }

    /**
     * 调度时间切换方法
     */
    var switchShowItem = function (dialog, timesRow, timeRange, dayTime, interval, dayMonthYear) {
        var _onoff = $.fn.onoff;

        $.fn.onoff = function (value) {

            var element = $(this);
            if (value) {
                element.show();
            } else {
                element.hide();
            }
            element.find('input').each(function (index, ele) {
                var role = $(ele).attr('ui-role');
                if (role == 'validatebox' || role == 'numberbox') {
                    !value ? $(ele)[role]('disable') : $(ele)[role]('enable');
                }
            });
        }
        dialog.find('.times-row').onoff(timesRow);
        dialog.find('.times-board').empty();
        if (timeRange) {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: true}).validatebox('validate');
        } else {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: false}).validatebox('validate');
        }
        dialog.find('.day-of-time-range-row').onoff(timeRange);
        dialog.find('.day-of-time-row').onoff(dayTime);
        dialog.find('.time-interval-row').onoff(interval);
        if (interval && dayMonthYear != undefined) {

            dialog.find('.time-of-day').onoff(dayMonthYear == 1);
            dialog.find('input.time-of-day').hide().radio('check', dayMonthYear == 1 ? 'outer-day' : '');
            dialog.find('.day-of-month').onoff(dayMonthYear == 2);
            dialog.find('input.day-of-month').hide().radio('check', dayMonthYear == 2 ? 'outer-month' : '');
            dialog.find('.month-of-year').onoff(dayMonthYear == 3);
            dialog.find('input.month-of-year').hide().radio('check', dayMonthYear == 3 ? 'outer-year' : '');
        }
        $.fn.onoff = _onoff;
    }

    /**
     * 初始化任务配置，调度配置，容错机制页面
     * @param dialog
     * @param job
     */
    var initFormData = function (dialog, job) {
        dialog.find("#tempo-task-xunhuanfangshi").show();
        job = job || {};
        var endtime = job.trigger.endtime;
        if (endtime != undefined && endtime != null && endtime.indexOf("T") != -1) {
            job.trigger.endtime = job.trigger.starttime;
        }
        TempoUtils.parserUi(dialog, job);
        //任务提交报错重试机制
        dialog.find('select[name="retry"]').selectmenu({
            selectFirst: true,
            disabled: true,
            change: function (e, ui) {
                changeRunErrorTrigger(ui.item.value)
            }
        });
        //重试次数
        var changeRunErrorTrigger = function (value) {
            if (value == "0") {
                dialog.find("td[name=retryNum]").hide();
            } else {
                dialog.find("td[name=retryNum]").show();
            }
        }

        dialog.find('[name="starttime"]').validatebox({readonly: true, validator: true}).datepicker({
            dateFormat: "yy-mm-dd",
            changeYear: true,
            changeMonth: true,
            onSelect: function (value) {
            },
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                dialog.find('[name="endtime"]').datepicker("option", "minDate", d2str);
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        });

        dialog.find('[name="endtime"]').validatebox({readonly: true, validator: true}).datepicker({
            dateFormat: "yy-mm-dd",
            changeYear: true,
            changeMonth: true,
            onSelect: function (value) {
            },
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                dialog.find('[name="starttime"]').datepicker("option", "maxDate", d2str);
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        });

        dialog.find('.timefield').timepicker({
            onClose: function () {
                if ($(this).val()) {
                    $(this).validatebox('response', $(this).val());
                }
            },
            onSelect: function () {

            },
            timeInput: true
        });

        var internalInput = dialog.find('input[name=interval]');
        dialog.find('select[name="triggertype"]').selectmenu({
            selectFirst: false,
            change: function (e, ui) {
                console.log(e, ui);
                changeTriggerType(ui.item.value);
            }
        });
        var changeWidthByScreen = function (screenWidth, value) {
            if (screenWidth == 1920) {
                if (value == '0' || value == '1' || value == '2') {
                    // $this.find('.tempo-task-td-center').css("width","108px");
                } else {
                    $this.find('.tempo-task-td-width').css("width", "293px");
                }
            } else if (screenWidth == 1600) {
                $this.find('.tempo-task-td-width').css("width", "180px");
                $this.find('.tempo-task-td-center').css("width", "80px");
            } else if (screenWidth == 1366) {
                $this.find('.tempo-task-td-right').css("width", "175px");

            }
        }

        var changeTriggerType = function (value) {

            var screenWidth = window.screen.width;
            if (value == "-2") {
                //分钟
                switchShowItem(dialog, false, true, false, true, 1);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-minute"));
                internalInput.numberbox({max: 59, min: 1}).val(30);
                changeWidthByScreen(screenWidth);
            } else if (value == "-1") {
                //小时
                switchShowItem(dialog, false, true, false, true, 1);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-hour"));
                internalInput.numberbox({max: 23, min: 1}).val(3);
                changeWidthByScreen(screenWidth);
            } else if (value == "0") {
                //天
                switchShowItem(dialog, false, false, true, true, 3);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-day"));
                internalInput.numberbox({max: 31, min: 1}).val(1);
                changeWidthByScreen(screenWidth, value);
            } else if (value == "1") {
                //周
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-week"));
                switchShowItem(dialog, true, false, true, false);
                buildWeeks(dialog);
                internalInput.numberbox({max: 6, min: 1}).val(1);
                changeWidthByScreen(screenWidth, value);
            } else if (value == "2") {
                //月
                switchShowItem(dialog, true, false, true, true, 2);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-month"));
                buildDays(dialog);
                internalInput.numberbox({max: 11, min: 1}).val(1);
                changeWidthByScreen(screenWidth, value);
            }
            internalInput.numberbox("doValidate");
        }

        //调度名称
        if (!$.isEmptyObject(job)) {
            dialog.find('input[name="starttime"]').val(job.trigger.starttime);
            dialog.find('input[name="endtime"]').val(job.trigger.endtime);
            dialog.find('input[name="stime"]').val(job.trigger.stime);
            dialog.find('input[name="etime"]').val(job.trigger.etime);
            dialog.find('select[name="priority"]').val(job.trigger.priority).selectmenu('refresh');
            dialog.find('input[name="id"]').val(job.id);
            dialog.find('input[name="name"]').val(job.trigger.name);
            dialog.find('select[name="triggertype"]').val(job.trigger.triggertype).selectmenu('refresh');
            changeTriggerType(job.trigger.triggertype);
            internalInput.val(job.trigger.interval);
            if (job.trigger.rundate) {
                var days = job.trigger.rundate.split(",");
                if (job.trigger.triggertype == '1') {
                    dialog.find('input[name=dayofweek]').each(function () {
                        var $this = $(this);
                        if (days.indexOf($this.val()) > -1) {
                            $this.checkbox('check', $this.val());
                        }
                    });
                } else if (job.trigger.triggertype == '2') {
                    dialog.find('input[name=dayofmonth]').each(function () {
                        var $this = $(this);
                        if (days.indexOf($this.val()) > -1) {
                            $this.checkbox('check', $this.val());
                        }
                    });
                }
            }
            if (job.trigger.runType) {
                dialog.find('input[name=runType]').radio('check', job.trigger.runType);
            }
            if ((job.trigger.triggertype == '-2' || job.trigger.triggertype == '-1')
                && job.trigger.runType != 'inner-day' && job.trigger.runType != 'outer-day') {
                dialog.find('input[name=runType]').radio('check', 'inner-day');
            }
            if (job.trigger.retry == undefined || job.trigger.retry == "") {
                job.trigger.retry = 0;
            }
            if (job.trigger.retryNum == undefined || job.trigger.retryNum == "") {
                job.trigger.retryNum = 1
            }
            dialog.find('select[name=retry]').val(job.trigger.retry).selectmenu('refresh');
            changeRunErrorTrigger(job.trigger.retry)
            dialog.find('input[name=retryNum]').numberbox({
                disabled: true,
                required: true,
                value: job.trigger.retryNum
            });
        } else {
            dialog.find('select[name="triggertype"]').val(0).selectmenu('refresh');
            changeTriggerType(0);
            dialog.find('input[name=starttime]').val(DateUtils.formatDate(new Date()));
        }
    }

    var getFlowParams = function (type, paramValueInput, value, nodeType) {
        var pss = [];
        if (type == 'datasource') {
            var process = $("<div/>").tempoprogressbar();
            $.ajax({
                url: contextPath + '/api/ai/node/io/list-datasources',
                type: 'post',
                success: function (rs) {
                    process.tempoprogressbar("destroy");
                    var data = rs.data;
                    var itemHtml = [];
                    for (var i = 0; i < data.length; i++) {
                        var dataItem = data[i];
                        // 屏蔽模型数据源、presto数据源、impala数据源
                        if (nodeType == 'readrdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
                                continue;
                            }
                        }
                        if (nodeType == 'writerdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }

                        if (nodeType == 'readhive') {
                            if (dataItem.type != 'hive') {
                                continue;
                            }
                        }
                        if (nodeType == "readtaosdb") {
                            if (dataItem.type != "taosDB") {
                                continue;
                            }
                        }
                        if(nodeType == 'writehive'){
                            if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
                                continue;
                            }
                        }
                        if (nodeType == "readinfluxdb") {
                            if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
                                continue;
                            }
                        }
                        if( nodeType == "readiotdb"){
                            if (dataItem.type != 'iotdb') {
                                continue;
                            }
                        }
                        if( nodeType == "writeiotdb"){
                            //不是iotdb  或者不能写入
                            if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }
                        itemHtml.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
                    }
                    var html = itemHtml.join('');
                    paramValueInput.html(html);
                    paramValueInput.selectmenu({
                        editable: false,
                        width: 150,
                        disabled: true,
                        labelForTitle: true
                    }).selectmenu('setValue', value).selectmenu('refresh');
                }
            });
        } else {
            var items = TempoMineUtils.getConstFlowParams();
            if (items) {
                for (name in items) {
                    pss.push('<option value="' + name + '">' + items[name] + '</option>')
                }
            }
            var html = pss.join('');
            paramValueInput.html(html);
            paramValueInput.selectmenu({
                editable: true,
                width: 150,
                labelForTitle: true
            }).selectmenu('setValue', value);
        }
    }

    /**
     * 初始化页面
     * @param dialog
     * @param ps
     */
    var initParamGrid = function (dialog, ps) {
        var grid = dialog.find('#setFlowParamTable');
        dialog.find('#task-flowParamsContainer').show();
        dialog.find('#tempo-mine-flow-param').show();
        if (ps && ps.length > 0) {
            var count = 0;
            var flag = false;
            for (var i = 0; i < ps.length; i++) {
                // 屏蔽系统参数
                if ('system.appId' == ps[i].paramName) {
                    flag = true;
                    continue;
                }
                var tr = $('<tr>').appendTo(grid);
                var p = ps[i];
                var paramName = p.paramName;
                var paramValue = p.paramValue;
                var paramType = p.paramType;
                var paramId = p.paramId;
                var nodeType = p.nodeType;
                // 获取流程参数说明，兼容一下，以前没有置为空
                var paramDesc = "";
                if (p.paramDesc) {
                    paramDesc = p.paramDesc;
                }
                if (!paramName) {
                    continue;
                }
                if ("configResources" == paramType) {
                    count++;
                    continue;
                }
                var paramNameTd = $('<td>').appendTo(tr);
                var paramNameInput = $('<input name="paramName">').addClass('flow_paramname').appendTo(paramNameTd).val(paramName);
                var paramTypeInput = $('<input name="paramType" type="hidden">').addClass('flow_paramtype').appendTo(paramNameTd).val(paramType);
                var paramTypeInput = $('<input name="paramId" type="hidden">').addClass('flow_paramid').appendTo(paramNameTd).val(paramId);
                var paramValueTd = $('<td>').appendTo(tr);
                var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
                paramNameInput.validatebox({width: 100, readonly: true, disabled: 'disabled'});
                // 在表格中添加流程参数说明
                var paramDescTd = $('<td>').appendTo(tr);
                var paramDescInput = $('<input name="paramDesc">').addClass('flow_paramdesc').appendTo(paramDescTd).val(paramDesc);
                // 为流程参数说明添加不能修改限制
                paramDescInput.validatebox({width: 100, readonly: true, disabled: 'disabled'});

                paramNameInput.attr('title', paramName);
                getFlowParams(paramType, paramValueInput, paramValue, nodeType);
                // 流程参数说明 值回显
                paramDescInput.attr('title', paramDesc);
            }
            if (count == ps.length) {
                dialog.find('#task-flowParamsContainer').hide();
            }
            if (ps.length == 1 && flag) {
                dialog.find('#task-flowParamsContainer').hide();
            }
        } else {
            dialog.find('#task-flowParamsContainer').hide();
        }
    }

    /**
     * 校验表单
     */
    var validateForm = function (dialog) {
        // 校验调度任务表单中的数据
        var v = dialog.find('form').formValidate();
        var jobconfig = TempoUtils.getRecord(dialog.find('form'));
        return v && (function () {
            console.log(jobconfig);
            var jobconfig = dialog.find('#tempo-mine-task-flow-config').serializeArray();
            var startTime = null;
            var endTime = null;
            for (var i = 0; i < jobconfig.length; i++) {
                var jobConfigItem = jobconfig[i];
                var curName = jobConfigItem["name"];
                var curValue = jobConfigItem["value"];
                if (curName == "starttime") {
                    startTime = curValue;
                }
                if (curName == "endtime") {
                    endTime = curValue;
                }
            }

            if (startTime && endTime) {
                var s = new Date(startTime);
                var e = new Date(endTime);
                if (s.getTime() > e.getTime()) {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.shengxiaoshijianerror"), height: 180});
                    return false;
                }
            }

            if (jobconfig.stime && jobconfig.etime) {
                if (jobconfig.stime >= jobconfig.etime && jobconfig.runType == 'inner-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.kaishishijianerror"), height: 180});
                    return false;
                }
                if (jobconfig.stime == jobconfig.etime && jobconfig.runType == 'outer-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.schedule-stime-not-equls-etime"), height: 180});
                    return false;
                }
            }
            return true;
        })();
    }
    var alert = function (text) {
        $("<div/>").alert({
            msg: text,
            title: TempoUtils.locale("mine.prompt")
        });
    }

    var saveTaskConfig = function (dialog, oldjob) {
        //开始的日期
        var startTime = dialog.find('input[name="starttime"]').val();
        //结束的日期
        var endTime = dialog.find('input[name="endtime"]').val();
        if ($this.find("#triggertype").val() == "-2" || $this.find("#triggertype").val() == "-1") {
            if (startTime == endTime) {
                //开始具体时刻
                var stime = $this.find(".tempo-stime").val();
                var etime = $this.find(".tempo-etime").val();
                if ("" == etime) {
                    alert("结束时间不能为空!");
                    return;
                }
                var newStime = startTime + " " + stime;
                var newEndtime = endTime + " " + etime;
                if (new Date(newStime).getTime() > new Date(newEndtime).getTime()) {
                    alert("日期为同一天时，开始时间不能大于结束时间!");
                    return;
                }
            }
        } else {
            var currentTime = dialog.find('.day-of-time-row input[name="stime"]').val();
            if (currentTime == "") {
                alert("请选择具体时间!");
                return;
            }
        }

        if (startTime == "") {
            alert("请选择生效日期起始时间!");
            return;
        }

        if (!validateForm(dialog)) {
            return;
        }
        var job = {
            trigger: {},
            publishFlowIds: []
        };
        job.id = oldjob.id;
        job.jobId = oldjob.jobId;
        job.creator = oldjob.creator;
        job.createTime = oldjob.createTime;
        job.trigger.id = oldjob.jobId;

        var triggerParam = {};
        var trigger = job.trigger;
        //调度信息数组
        var jobconfig = dialog.find('#tempo-mine-task-flow-config').serializeArray();
        var starttime;
        var endtime;
        for (var i = 0; i < jobconfig.length; i++) {
            if (jobconfig[i].name == 'starttime') {
                starttime = jobconfig[i].value;
            }
            if (jobconfig[i].name == 'endtime') {
                endtime = jobconfig[i].value;
            }
        }
        var date = new Date(endtime);
        date.setDate(date.getDate());
        if (starttime == endtime) {
            for (var i = 0; i < jobconfig.length; i++) {
                if (jobconfig[i].name == 'endtime') {
                    jobconfig[i].value = date;
                }
            }
        }

        //解决保存星期、日多值无法保存问题
        //添加对复选框值的处理，转变为一个属性值
        $.each(jobconfig, function (index, item) {
            if (!item.name.startsWith('flow_')) {
                if (trigger[item.name] && item.name != 'stime') {
                    if (Array.isArray(trigger[item.name])) {
                        trigger[item.name].push(item.value);
                    } else {
                        trigger[item.name] = [trigger[item.name], item.value];
                    }
                } else {
                    trigger[item.name] = item.value;
                }
            }
        });
        //解决多个stime无法确定问题
        if (trigger.triggertype == '-1' || trigger.triggertype == '-2') {
            trigger['stime'] = dialog.find('.day-of-time-range-row input[name=stime]').val();
        } else {
            trigger['stime'] = dialog.find('.day-of-time-row input[name=stime]').val();
        }
        trigger['retryNum'] = dialog.find("input[name=retryNum]").val()
        //解决IE10下面选中保存不了问题
        trigger.retry = dialog.find('select[name=retry]').val();

        if ((dialog.find('input[name=dayofweek]').length && !trigger['dayofweek'])
            || (dialog.find('input[name=dayofmonth]').length && !trigger['dayofmonth'])) {
            $("<div/>").alert({msg: TempoUtils.locale("mine.qingxuanzeyunxingshijian"), height: 180});
            return false;
        }
        //处理数组类型值，转换为逗号分割的字符串
        Array.isArray(trigger['dayofweek']) && (trigger['rundate'] = trigger['dayofweek'].join(','));
        Array.isArray(trigger['dayofmonth']) && (trigger['rundate'] = trigger['dayofmonth'].join(','));
        trigger['dayofweek'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofweek']);
        trigger['dayofmonth'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofmonth']);
        delete trigger['dayofweek'];
        delete trigger['dayofmonth'];
        console.log(JSON.stringify(trigger))
        trigger.interval = Number(trigger.interval);
        if (trigger.retryNum) trigger.retryNum = Number(trigger.retryNum);

        var oldJobParamJson = JSON.parse(oldjob.trigger.param);
        triggerParam.flowsInJob = oldJobParamJson.flowsInJob;
        if (!triggerParam.flowsInJob || triggerParam.flowsInJob == undefined) {
            var relatedFlow = [];
            var rflowObj = {};
            rflowObj["flow_current"] = oldjob.publishFlowIds;
            relatedFlow.push(rflowObj);
            triggerParam.flowsInJob = relatedFlow;
        }
        job.publishFlowIds = oldjob.publishFlowIds;
        job.publishFlowNames = oldjob.publishFlowNames;
        //流程配置参数
        triggerParam.flowsParam = {};
        //保存流程参数，环境参数，Python资源限制
        var currentFlowParamsResult = getCurrentFlowParamsNew(dialog);
        if (currentFlowParamsResult === false) {
            return;
        } else {
            triggerParam.flowsParam[oldjob.publishFlowIds] = currentFlowParamsResult;
        }

        job.trigger.param = JSON.stringify(triggerParam);

        var process = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/app/schedule/job/update';
        $.ajax({
            url: url,
            type: 'post',
            data: JSON.stringify(job),
            contentType: 'application/json',
            success: function (obj) {
                process.tempoprogressbar("destroy");
                if (obj && obj.data && obj.data.status) {
                    $('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                    refreshJob();
                    configInitDisabled(job);
                    $(".tempo-app-task-view").find("#ca-name").text(job.trigger.name);
                    $("#tempo-ai-task-index-view-right-container").find("#ca-name").text(job.trigger.name);
                    $(".theme-container").find(".tempo-theme-public-tree").gtree("updateItemName", job.id, job.trigger.name);
                } else {
                    $("<div/>").alert({msg: obj.data.error, height: 180, width: 400});
                }
            },
            error: function (data) {
                process.tempoprogressbar("destroy");
            }
        });
    }

    /**
     * 保存流程参数，环境参数，Python资源限制
     * @param dialog
     * @returns {boolean|*[]}
     */
    var getCurrentFlowParamsNew = function (dialog) {
        editStatus.flowParams = false;
        //保存事件
        var flowParams = [];
        for (var i = 1; i <= flowArray.length; i++) {
            var paramValue = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(2)").find("select").selectmenu("getValue");
            if (TempoMineUtils.disableInputElement(paramValue)) return false;
            var obj = {
                paramName: paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(1)").text(),
                paramValue: paramValue,
                paramDesc: paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(3)").text()
            };
            if (flowArray[i - 1].paramType) {
                obj.paramType = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(4)").text()
            }
            if (flowArray[i - 1].nodeType) {
                obj.nodeType = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(5)").text()
            }
            if (flowArray[i - 1].paramId) {
                obj.paramId = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(6)").text()
            }
            flowParams.push(obj);
        }

        //保存修改流程参数之后进行回调
        flowParamInitSave();
        saveEnvInfoTable();
        savePythonLimitTable();
        var resourceParamsNew = JSON.stringify((resPar.filter(function (v) {
            if (v["$configResources$"]) return true;
        }))[0]);
        var resourceParamsJson = JSON.parse(resourceParamsNew);
        var configResources = JSON.parse(resourceParamsJson.$configResources$);

        for (var key in configResources) {
            var rsValue = configResources[key];
            if (rsValue && rsValue != null) {
                rsValue = rsValue.trim();
                var param = {};
                if ("cpu" == key) {
                    param.paramName = "driverCpu";
                }
                if ("mem" == key) {
                    param.paramName = "driverMemory";
                }
                if ("gpu" == key) {
                    param.paramName = "gpu";
                }
                if ("execcpu" == key) {
                    param.paramName = "totalExecutorCores";
                }
                if ("execmemory" == key) {
                    param.paramName = "executorMemory";
                }
                if ("cacheconfig" == key) {
                    param.paramName = "cacheType";
                }
                if ("executors" == key) {
                    param.paramName = "exeProcessNum";
                }
                if ("limitCpu" == key) {
                    param.paramName = "limitExtendCpu";
                }
                if ("limitMemory" == key) {
                    param.paramName = "limitExtendMemory";
                }
                param.paramValue = rsValue;
                param.paramId = "";
                param.paramType = "configResources";
                if ((!$.isEmptyObject(param)) && (param.paramName != undefined)) {
                    flowParams.push(param);
                }
            }
        }
        return flowParams;
    }

    /**
     * 获取当前流程参数
     * @param dialog
     * @returns {[]}
     */
    var getCurrentFlowParams = function (dialog) {
        var paramsTable = dialog.find('#task-flowParamsContainer table');
        var currentFlowParams = []
        var paramsLine = paramsTable.find('tbody tr');
        paramsLine.each(function (i) {

            var paramName = $(this).find('input.flow_paramname').val();
            var paramType = $(this).find('input.flow_paramtype').val();
            var paramId = $(this).find('input.flow_paramid').val();
            var paramValue = $(this).find('select.flow_paramvalue').selectmenu('getValue');
            // 获取流程参数中说明字段
            var paramDesc = $(this).find('input.flow_paramdesc').val();
            if (paramName) {
                var param = {};
                param.paramName = paramName;
                param.paramValue = paramValue;
                param.paramId = paramId;
                param.paramType = paramType;
                // 存储流程参数说明
                param.paramDesc = paramDesc;
                if (!$.isEmptyObject(param)) {
                    currentFlowParams.push(param);
                }
            }
        });
        var rowNew = {"type": "async"};
        Eventbus.trigger("saveFlowParamGrid.mine", $this.find("#flow-params"), $this.find("#task-res-config"), rowNew);
        delete rowNew["type"];
        var resourceParams = rowNew.flowParams;
        var resourceParamsJson = JSON.parse(resourceParams);
        var configResources = JSON.parse(resourceParamsJson[0].$configResources$);

        for (var key in configResources) {
            var rsValue = configResources[key];
            if (rsValue != null) {
                var param = {};
                if ("cpu" == key) {
                    param.paramName = "driverCpu";
                }
                if ("mem" == key) {
                    param.paramName = "driverMemory";
                }

                if ("execcpu" == key) {
                    param.paramName = "totalExecutorCores";

                }
                if ("execmemory" == key) {
                    param.paramName = "executorMemory";
                }

                if ("cacheconfig" == key) {
                    param.paramName = "cacheType";
                }
                if ("executors" == key) {
                    param.paramName = "exeProcessNum";
                }
                if ("limitCpu" == key) {
                    param.paramName = "limitExtendCpu";
                }
                if ("limitMemory" == key) {
                    param.paramName = "limitExtendMemory";
                }
                param.paramValue = rsValue;
                param.paramId = "";
                param.paramType = "configResources";
                if (!$.isEmptyObject(param)) {
                    currentFlowParams.push(param);
                }
            }
        }
        return currentFlowParams;
    }

    var setFlowParams = function (dialog, job) {
        var flowParams = job ? JSON.parse(job.trigger.param) : null;
        var flowParam = null;
        if (flowParams != null) {
            if (flowParams.flowsParam) {
                flowParam = flowParams.flowsParam;
            } else {
                flowParam = flowParams;
            }
        }
        dialog.find('#task-flowParamsContainer').hide();
        var paramLabel = TempoUtils.locale("mine.publish-mine-job-param-label");
        dialog.find("#publish-mine-job-param-label").text(job.publishFlowNames + '-' + paramLabel);
        var grid = dialog.find('#setFlowParamTable').find('tbody').empty();
        if (flowParam != null) {
            var params = flowParam[job.publishFlowIds];
            if (!params || params.length == 0) {
                $.ajax({
                    // 获取流程参数
                    url: contextPath + "/api/ai/app/schedule/flowparams/get/" + job.publishFlowIds,
                    type: 'post',
                    success: function (result) {
                        if (result && result.data && result.data.length > 0) {
                            initParamGrid(dialog, result.data);
                        }
                    }
                });
            } else {
                initParamGrid(dialog, params);
            }
        }
    }

    /**
     * 停止任务
     */
    var stopJob = function () {
        var progressbar = $("<div/>").tempoprogressbar();
        $.ajax({
            url: contextPath + '/api/ai/app/schedule/job/stop',
            type: 'post',
            data: {
                id: job.id,
                triggerId: job.jobId
            },
            dataType: 'json',
            success: function (obj) {
                progressbar.tempoprogressbar("destroy");
                if (obj.success) {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.publish-job-killed"), height: 180});
                    $("#tempo-task-stop-btn" + id).removeClass("tempo-api-icon-18-position-task-stop").addClass("tempo-api-icon-18-position-task-stop-disabled");
                } else {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.publish-job-notexists"), height: 180});
                }
                refreshJob();
            }
        });
    }

    var manualJob = function () {
        var progressbar = $("<div/>").tempoprogressbar();
        $.ajax({
            url: contextPath + "/api/ai/app/schedule/job/manual",
            type: 'post',
            data: {
                id: job.id,
                triggerId: job.jobId
            },
            dataType: 'json',
            success: function (obj) {
                progressbar.tempoprogressbar("destroy");
                if (obj.success) {
                    $("#tempo-task-manual-btn" + id).removeClass("tempo-api-icon-18-position-task-manual").addClass("tempo-api-icon-18-position-task-manual-disabled");
                    $("<div/>").alert({
                        msg: "任务开始执行",
                        height: 180
                    });
                } else {
                    $("<div/>").alert({
                        msg: TempoUtils.locale("mine.renwuzhixingzhong"),
                        height: 180
                    });
                }
                refreshJob();
            }
        });
    }

    var refreshJob = function () {
        $.ajax({
            url: contextPath + '/api/ai/mine/publish/listJobInfo',
            type: 'post',
            dataType: 'json',
            data: {
                id: args.id
            },
            success: function (result) {

                if ("true" == result.flag) {
                    job = result.job;
                    refreshPauseStatus(result);
                }
            }
        });
    }

    /**
     * 暂停任务
     */
    var pauseJob = function () {

        var progressbar = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/app/schedule/job/pause';
        if (job.trigger.status == 'PAUSED' || job.trigger.status == 'PAUSED_BLOCKED') {
            url = contextPath + '/api/ai/app/schedule/job/restart'
        } else if (job.trigger.status == 'COMPLETE') {
            progressbar.tempoprogressbar("destroy");
            $("<div/>").alert({
                msg: TempoUtils.locale("mine.renwuyijingwancheng"),
                height: 180
            });
            return false;
        }
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data: {
                id: job.id, triggerId: job.jobId
            },
            success: function (obj) {
                progressbar.tempoprogressbar("destroy");
                if (job.status != 'PAUSED') {
                    if (obj && obj.success == false) {
                        $("<div/>").alert({
                            msg: TempoUtils.locale("mine.renwuyijingyunxing"),
                            height: 180
                        });
                    }
                }
                refreshJob();
            }
        });
    }

    /**
     * 初始化页面组件禁用
     * @param job
     */
    var configInitDisabled = function (job) {
        var taksConfigForm = $this.find("#task-res-config");
        var configForm = $this.find(".tempo-task-configuration");
        configForm.find("input[name='name']").attr("disabled", "disabled");
        configForm.find("input[name='starttime']").attr("disabled", "disabled");
        configForm.find("input[name='endtime']").attr("disabled", "disabled");
        configForm.find("input[name='starttime']").css("border", "");
        configForm.find("input[name='endtime']").css("border", "");
        configForm.find("input[name='stime']").css("border", "");
        configForm.find("input[name='etime']").css("border", "");
        configForm.find("input[name='retry']").attr("disabled", "disabled");
        configForm.find("input[name='interval']").attr("disabled", "disabled");
        configForm.find("input[name='runType']").attr("disabled", "disabled");
        configForm.find("input[name='dayofweek']").attr("disabled", "disabled");
        configForm.find("input[name='dayofmonth']").attr("disabled", "disabled");
        configForm.find("input[name=retryNum]").attr("disabled", "disabled");
        taksConfigForm.find("input").attr("disabled", "disabled");
        configForm.find("select.tempo-selectmenu").selectmenu("option", "disabled", true);
        $this.find("#tempo-task--param-save" + id).text("配置");
        configForm.find('.datefield').datepicker("disable");
        configForm.find('.timefield').timepicker("disable");
        editStatus.all = false;
        envInitSave();
    }

    var configInitEdit = function (job) {
        var taksConfigForm = $this.find("#task-res-config");
        var configForm = $this.find("#tempo-mine-task-flow-config");
        configForm.find("input[name='name']").removeAttr("disabled");
        configForm.find("input[name='starttime']").removeAttr("disabled");
        configForm.find("input[name='endtime']").removeAttr("disabled");
        configForm.find("input[name='starttime']").css("border", "1px solid #c0c9d5");
        configForm.find("input[name='endtime']").css("border", "1px solid #c0c9d5");
        configForm.find("input[name='stime']").css("border", "1px solid #c0c9d5");
        configForm.find("input[name='etime']").css("border", "1px solid #c0c9d5");
        configForm.find("input[name='retry']").removeAttr("disabled");
        configForm.find("input[name='interval']").removeAttr("disabled");
        configForm.find("input[name='runType']").removeAttr("disabled");
        configForm.find("input[name='dayofweek']").removeAttr("disabled");
        configForm.find("input[name='dayofmonth']").removeAttr("disabled");
        taksConfigForm.find("input").removeAttr("disabled");
        configForm.find("select.tempo-selectmenu").selectmenu("option", "disabled", false);
        configForm.find("input[name=retryNum]").removeAttr("disabled");
        $this.find("#tempo-task--param-save" + id).text("保存");
        configForm.find('.datefield').datepicker("enable");
        configForm.find('.timefield').timepicker("enable");
        $('select[name="paramValue"]').selectmenu('enable');
        editStatus.all = true;
        editStatus.flowParams = true;
        editStatus.envInfo = true;
        editStatus.limit = true;
        //流程参数表格转变为可编辑状态
        editFlowParamsTable();
        //环境参数表格转变为可编辑状态
        editEnvInfoTable();
        //Python资源限制表格转变为可编辑状态
        editPythonLimitTable();
    }

    /**
     * 绑定页面事件
     * @param job
     */
    var bindEvent = function (job) {
        $this.find("#tempo-task--param-save" + id).button({
            click: function (e) {
                if (!editStatus.all) {
                    configInitEdit(job);
                } else {
                    saveTaskConfig($this.find(".tempo-mine-flow-job-container"), job);

                }
            }
        });

        $this.find("#tempo-task-stop" + id).unbind("click").bind("click", function (e) {
            if (!$(this).hasClass("tempo-task-button-disabled")) {
                stopJob();
            }
        });

        $this.find("#tempo-task-manual" + id).unbind("click").bind("click", function (e) {
            if (!$(this).hasClass("tempo-task-button-disabled")) {
                manualJob();
            }
        });

        refreshJob();
        $this.find("#tempo-task-pause" + id).unbind("click").bind("click", function (e) {
            if (!$(this).hasClass("tempo-task-button-disabled")) {
                pauseJob();
            }
        });
    }

    /**
     * 刷新调度按钮状态
     * @param job
     */
    var refreshStopOrManualStatus = function (job) {
        var settimeout = setTimeout(function () {
            $.ajax({
                url: contextPath + '/api/ai/mine/publish/getTaskStatus',
                type: 'post',
                dataType: 'json',
                data: {
                    id: job.id
                },
                success: function (response) {
                    if ($("#tempo-task-stop-btn" + id).length == 0) {
                        clearTimeout(settimeout);
                    }
                    if (response.success && response.data == "true") {
                        $("#tempo-task-stop-btn" + id).removeClass("tempo-api-icon-18-position-task-stop-disabled").addClass("tempo-api-icon-18-position-task-stop");
                        $("#tempo-task-manual-label" + id).addClass("tempo-task-label-disabled");
                        $("#tempo-task-stop" + id).removeClass("tempo-task-button-disabled");
                        $("#tempo-task-manual" + id).addClass("tempo-task-button-disabled");
                        $("#tempo-task-manual-btn" + id).removeClass("tempo-api-icon-18-position-task-manual").addClass("tempo-api-icon-18-position-task-manual-disabled");
                    } else {
                        $("#tempo-task-stop-btn" + id).removeClass("tempo-api-icon-18-position-task-stop").addClass("tempo-api-icon-18-position-task-stop-disabled");
                        $("#tempo-task-manual-btn" + id).removeClass("tempo-api-icon-18-position-task-manual-disabled").addClass("tempo-api-icon-18-position-task-manual");
                        $("#tempo-task-manual-label" + id).removeClass("tempo-task-label-disabled");
                        $("#tempo-task-stop" + id).addClass("tempo-task-button-disabled");
                        $("#tempo-task-manual" + id).removeClass("tempo-task-button-disabled");
                    }
                    refreshStopOrManualStatus(job);
                }
            });
        }, 2000);
    }

    /**
     * 刷新状态
     * @param result 返回调度任务信息，避免二次查询调度任务接口
     */
    var refreshPauseStatus = function (result) {
        if ("COMPLETE" == job.trigger.status || "PAUSED" == job.trigger.status || "PAUSED_BLOCKED" == job.trigger.status) {
            $("#tempo-task-pause-or-start" + id).text("开启任务");
            $("#tempo-task-pause-or-start-btn" + id).removeClass("tempo-api-icon-18-position-task-pause");
            $("#tempo-task-pause-or-start-btn" + id).addClass("tempo-api-icon-18-position-task-start");
        } else {
            $("#tempo-task-pause-or-start" + id).text("暂停任务");
            $("#tempo-task-pause-or-start-btn" + id).removeClass("tempo-api-icon-18-position-task-start");
            $("#tempo-task-pause-or-start-btn" + id).addClass("tempo-api-icon-18-position-task-pause");
        }

        if ("true" == job.isRunning) {
            $("#tempo-task-stop-btn" + id).removeClass("tempo-api-icon-18-position-task-stop-disabled").addClass("tempo-api-icon-18-position-task-stop");
            $("#tempo-task-manual-btn" + id).removeClass("tempo-api-icon-18-position-task-manual").addClass("tempo-api-icon-18-position-task-manual-disabled");
            $("#tempo-task-manual-label" + id).addClass("tempo-task-label-disabled");

            $("#tempo-task-stop" + id).removeClass("tempo-task-button-disabled");
            $("#tempo-task-manual" + id).addClass("tempo-task-button-disabled");

        } else {
            $("#tempo-task-stop-btn" + id).removeClass("tempo-api-icon-18-position-task-stop").addClass("tempo-api-icon-18-position-task-stop-disabled");
            $("#tempo-task-manual-btn" + id).removeClass("tempo-api-icon-18-position-task-manual-disabled").addClass("tempo-api-icon-18-position-task-manual");
            $("#tempo-task-manual-label" + id).removeClass("tempo-task-label-disabled");

            $("#tempo-task-stop" + id).addClass("tempo-task-button-disabled");
            $("#tempo-task-manual" + id).removeClass("tempo-task-button-disabled");
        }
        //查询调度任务会调用两次查询接口导致系统日志记录两遍
        if ("true" == result.flag) {
            var resultJob = result.job;
            var taskStatusDesc = "生效";
            if (resultJob.trigger.status == "PAUSED" || resultJob.trigger.status == "PAUSED_BLOCKED") {
                taskStatusDesc = '暂停';
            } else if (resultJob.trigger.status == "COMPLETE") {
                taskStatusDesc = '失效';
            } else if (resultJob.trigger.status == "AWAIT") {
                taskStatusDesc = '等待';
            }
            $this.find(".task-runtStatus").html(taskStatusDesc).attr("id", resultJob.id);
        }
    }

    var refreshRunStatus = function () {
        var taskStatusDesc = "生效";
        if (firstJobStatus == "PAUSED" || job.trigger.status == "PAUSED_BLOCKED") {
            taskStatusDesc = '暂停';
        } else if (firstJobStatus == "COMPLETE") {
            taskStatusDesc = '失效';
        } else if (firstJobStatus == "AWAIT") {
            taskStatusDesc = '等待';
        }
        $this.find('#' + args.id).text(taskStatusDesc);
    }

    /**
     * 构建异步服务云模式的表格
     */
    var buildAsyncCloudHtml = function () {
        var html = "";
        html += '<tr>' +
            '<td class="app-task-config-env-td-label"><label for="driverCpu">管理CPU个数</label></td>' +
            '<td class="app-task-config-env-td-label"><label for="manageMemory">管理内存（GB）</label></td>' +
            '<td class="app-task-config-env-td-label"><label>执行器个数</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="manage-cpu-num">1</td>' +
            '<td name="manage-memory">1</td>' +
            '<td name="executor-num">1</td>' +
            '</tr>';
        html += '<tr>' +
            '<td class="app-task-config-env-td-label"><label>运行CPU个数</label></td>' +
            '<td class="app-task-config-env-td-label"><label>运行内存（GB）</label></td>' +
            '<td class="app-task-config-env-td-label"><label>缓存设置</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="run-cpu-num">1</td>' +
            '<td name="run-memory">1</td>' +
            '<td name="cache-config">1</td>' +
            '</tr>';
        html += '<tr>' +
            '<td class="app-config-env-td-label" sign="gpu"><label>管理GPU个数</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="gpu" sign="gpu">0</td>' +
            '</tr>';
        return html;
    };

    /**
     * 构建异步服务本地的表格
     */
    var buildAsyncLocalHtml = function () {
        var html = "";
        html += '<tr>' +
            '<td class="app-config-env-td-label"><label for="driverCpu">线程数</label></td>' +
            '<td class="app-config-env-td-label"><label for="manageMemory">内存（GB）</label></td>' +
            '<td class="app-config-env-td-label" sign="gpu"><label>管理GPU个数</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="manage-cpu-num">1</td>' +
            '<td name="manage-memory">1</td>' +
            '<td name="gpu" sign="gpu">0</td>' +
            '</tr>';
        return html;
    };

    /**
     * 获取环境参数的html
     * @returns {boolean}
     */
    var getEnvParamsHtml = function () {

        //获取配置参数
        var configResources = resPar.filter(function (v) {
            if (v.$configResources$ != null) {
                return true
            }
        });

        if (configResources.length > 0) {
            var json = JSON.parse(configResources[0]["$configResources$"]);
            if (Object.keys(json).length == 0) {
                return false;
            }
            //初始化执行环境
            var mode = json.mode || 'SYNC_ON_LOCAL';
            //默认为本地执行
            if (!EXCUTE_MODE[mode]) {
                mode = "SYNC_ON_LOCAL";
            }
            if (mode == "SYNC_ON_LOCAL") {
                //单机
                $(buildAsyncLocalHtml()).appendTo(envTable.find("tbody"));
                envTable.find('td[name="manage-cpu-num"]').html(json.cpu || 2);
                envTable.find('td[name="manage-memory"]').html(json.mem || 2);
            } else {
                //集群
                $(buildAsyncCloudHtml()).appendTo(envTable.find("tbody"));
                envTable.find('td[name="manage-cpu-num"]').html(json.cpu || 2);
                envTable.find('td[name="manage-memory"]').html(json.mem || 2);
                envTable.find('td[name="executor-num"]').html(json.executors);
                envTable.find('td[name="run-cpu-num"]').html(json.execcpu);
                envTable.find('td[name="run-memory"]').html(json.execmemory);
                envTable.find('td[name="cache-config"]').html(json.cacheconfig);
            }

            //判断是否开启GPU
            if (json.gpu) {
                envTable.find('td[sign="gpu"]').show();
                $(envTable.find('td[name="gpu"]')).text(json.gpu || 0);
            } else {
                envTable.find('td[sign="gpu"]').remove();
            }

            //清除空的tr
            var trs = envTable.find("tbody").find("tr");
            for (var i = 0; i < trs.length; i++) {
                if ($(trs[i]).html() === "") {
                    $(trs[i]).css("display", "none");
                }
            }

            //编辑管理CPU个数或者线程数
            var $mcn = $env.find('td[name="manage-cpu-num"]');
            if ($mcn && $mcn.length > 0) {
                var mcnValue = $mcn.text();
                $mcn.empty();
                var $mcnInput = $('<input name="manage-cpu-num-input"/>').val(mcnValue).appendTo($mcn);
                $mcnInput.numberbox({
                    required: true,
                    validator: true,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled");
            }
            //编辑管理内存或者内存
            var $mm = $env.find('td[name="manage-memory"]');
            if ($mm && $mm.length > 0) {
                var mmValue = $mm.text();
                $mm.empty();
                var $mmInput = $('<input name="manage-memory-input" />').val(mmValue).appendTo($mm);
                $mmInput.numberbox({
                    required: true,
                    validator: true,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled");
            }
            //编辑执行器个数
            var $en = $env.find('td[name="executor-num"]');
            if ($en && $en.length > 0) {
                var enValue = $en.text();
                $en.empty();
                var $enInput = $('<input name="executor-num-input" />').val(enValue).appendTo($en);
                $enInput.numberbox({
                    required: true,
                    validator: true,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled");
            }
            //编辑运行内存个数
            var $rcn = $env.find('td[name="run-cpu-num"]');
            if ($rcn && $rcn.length > 0) {
                var rcnValue = $rcn.text();
                $rcn.empty();
                var $rcnInput = $('<input name="run-cpu-num-input" />').val(rcnValue).appendTo($rcn);
                $rcnInput.numberbox({
                    required: true,
                    validator: true,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled");
            }
            //编辑运行内存
            var $rm = $env.find('td[name="run-memory"]');
            if ($rm && $rm.length > 0) {
                var rmValue = $rm.text();
                $rm.empty();
                var $rmInput = $('<input name="run-memory-input" />').val(rmValue).appendTo($rm);
                $rmInput.numberbox({
                    required: true,
                    validator: true,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled");
            }

            //编辑GPU
            if (json.gpu) {
                var $gpu = $env.find('td[name="gpu"]');
                if ($gpu && $gpu.length > 0) {
                    var gpuValue = $gpu.text();
                    $gpu.empty();
                    var $gpuInput = $('<input name="gpu" />').val(gpuValue).appendTo($gpu);
                    $gpuInput.numberbox({
                        required: true,
                        validator: true,
                        min: 0,
                        precision: 0
                    }).addClass("ui-state-disabled");
                }
            }

            //编辑缓存设置
            var $cc = $env.find('td[name="cache-config"]');
            if ($cc && $cc.length > 0) {
                var ccValue = $cc.text();
                $cc.empty();
                var $ccSelect = $('<select name="cache-config-select" />').appendTo($cc);
                var values = [];
                values.push({name: "NONE", value: 'NONE'},
                    {name: 'DISK_ONLY', value: 'DISK_ONLY'},
                    {name: 'DISK_ONLY_2', value: 'DISK_ONLY_2'},
                    {name: 'MEMORY_ONLY', value: 'MEMORY_ONLY'},
                    {name: 'MEMORY_ONLY_2', value: 'MEMORY_ONLY_2'},
                    {name: 'MEMORY_ONLY_SER', value: 'MEMORY_ONLY_SER'},
                    {name: 'MEMORY_ONLY_SER_2', value: 'MEMORY_ONLY_SER_2'},
                    {name: 'MEMORY_AND_DISK', value: 'MEMORY_AND_DISK'},
                    {name: 'MEMORY_AND_DISK_2', value: 'MEMORY_AND_DISK_2'},
                    {name: 'MEMORY_AND_DISK_SER', value: 'MEMORY_AND_DISK_SER'},
                    {name: 'MEMORY_AND_DISK_SER_2', value: 'MEMORY_AND_DISK_SER_2'},
                    {name: 'OFF_HEAP', value: 'OFF_HEAP'});
                for (var i in values) {
                    var value = values[i];
                    $('<option>').text(value.name).attr('value', value.value).appendTo($ccSelect);
                }
                ;
                $ccSelect.selectmenu().selectmenu('setValue', ccValue).selectmenu("option", "disabled", true);
            }
            //编辑执行环境
            var $mode = $env.find('td[name="mode"]');
            if ($mode && $mode.length > 0) {
                var modeValue = $mode.text();
                $mode.empty();
                var $modeSelect = $('<select name="mode-select" />').appendTo($mode);
                if (row.type == "sync" || row.type == "stream") {
                    //同步和流时应该判断系统是否支持yarn 支持的则可以切集群
                    $.ajax({
                        url: contextPath + "/api/ai/mine/getClusterParams",
                        type: 'post',
                        async: false,
                        success: function (rs) {
                            var result = rs.data;
                            var values = [];
                            values.push({
                                name: "本地",
                                value: 'SYNC_ON_LOCAL'
                            });
                            if (result && result.masterType.startsWith('yarn')) {
                                values.push({
                                    name: "集群",
                                    value: 'SYNC_ON_YARN'
                                });
                            }
                            ;
                            values.reverse();
                            for (var i in values) {
                                var value = values[i];
                                $('<option>').text(value.name).attr('value', value.value).appendTo($modeSelect);
                            }
                            ;
                            $modeSelect.selectmenu({
                                change: function (event, selected) {
                                    var val = selected.item.value;
                                    if ("SYNC_ON_LOCAL" == val) {
                                        $env.find('label[for="driverCpu"]').text("线程数");
                                        $env.find('label[for="manageMemory"]').text("内存（GB）");
                                    } else {
                                        $env.find('label[for="driverCpu"]').text("管理CPU个数");
                                        $env.find('label[for="manageMemory"]').text("管理内存（GB）");
                                    }
                                }
                            }).selectmenu("option", "disabled", true);
                        }
                    });

                }
                $modeSelect.selectmenu().selectmenu('setValue', EXCUTE_MODE[modeValue]).selectmenu("option", "disabled", true);
            }
            return true;
        } else {
            console.error('Parse param error: ', rowData);
        }
        return false;
    };

    /**
     * 环境参数配置表中的为可编辑状态
     */
    var editEnvInfoTable = function () {
        var that = $this;
        var $env = that.find("#tempo-mine-flow-env-info");

        //编辑管理CPU个数或者线程数
        var $mcn = $env.find('input[name="manage-cpu-num-input"]');
        if ($mcn && $mcn.length > 0) $mcn.removeClass("ui-state-disabled");
        //编辑管理内存或者内存
        var $mm = $env.find('input[name="manage-memory-input"]');
        if ($mm && $mm.length > 0) $mm.removeClass("ui-state-disabled");
        //编辑执行器个数
        var $en = $env.find('input[name="executor-num-input"]');
        if ($en && $en.length > 0) $en.removeClass("ui-state-disabled");
        //编辑运行内存个数
        var $rcn = $env.find('input[name="run-cpu-num-input"]');
        if ($rcn && $rcn.length > 0) $rcn.removeClass("ui-state-disabled");
        //编辑运行内存
        var $rm = $env.find('input[name="run-memory-input"]');
        if ($rm && $rm.length > 0) $rm.removeClass("ui-state-disabled");
        //编辑缓存设置
        var $cc = $env.find('select[name="cache-config-select"]');
        if ($cc && $cc.length > 0) $cc.selectmenu("option", "disabled", false);
        //编辑执行环境
        var $mode = $env.find('select[name="mode-select"]');
        if ($mode && $mode.length > 0) $mode.selectmenu("option", "disabled", false);
        //编辑gpu
        var $gpu = $env.find('input[name="gpu"]');
        if ($gpu && $gpu.length > 0) $gpu.removeClass("ui-state-disabled");
    }

    /**
     * 保存环境参数配置表参数
     */
    var saveEnvInfoTable = function () {
        //保存事件
        var rowNew = TempoUtils.clone(row);
        var configResources = resPar.filter(function (v) {
            if (v.$configResources$ != null) {
                return true
            }
        });
        if (configResources.length > 0) {
            var json = JSON.parse(configResources[0]["$configResources$"]);
            //编辑管理CPU个数或者线程数
            var cni = envTable.find('input[name=manage-cpu-num-input]');
            if (json.cpu && cni.length == 1) json.cpu = cni.val();
            //编辑管理内存或者内存
            var mmi = envTable.find('input[name=manage-memory-input]');
            if (json.mem && mmi.length == 1) json.mem = mmi.val();
            //编辑执行器个数
            var eni = envTable.find('input[name=executor-num-input]');
            if (json.executors && eni.length == 1) json.executors = eni.val();
            //编辑运行内存个数
            var rcni = envTable.find('input[name=run-cpu-num-input]');
            if (json.execcpu && rcni.length == 1) json.execcpu = rcni.val();
            //编辑运行内存
            var rmi = envTable.find('input[name=run-memory-input]');
            if (json.execmemory && rmi.length == 1) json.execmemory = rmi.val();
            //编辑缓存设置
            var ccs = envTable.find('select[name=cache-config-select]');
            if (json.cacheconfig && ccs.length == 1) json.cacheconfig = ccs.selectmenu("getValue");
            //编辑执行环境
            var ms = envTable.find('select[name=mode-select]');
            if (json.mode && ms.length == 1) json.mode = ms.selectmenu("getValue");
            //编辑gpu
            var gpu = envTable.find('input[name=gpu]');
            if (json.gpu && gpu.length == 1) json.gpu = gpu.val();

            var flowParams = resPar.map(function (v) {
                if (v.$configResources$ != null) {
                    return {$configResources$: JSON.stringify(json)};
                }
                return v;
            });
            rowNew.flowParams = JSON.stringify(flowParams);
            window.resPar = flowParams;
        } else {
            console.error('configResources error: ', configResources);
        }
    }

    /**
     * 保存页面后重新渲染
     */
    var envInitSave = function () {
        editStatus.envInfo = false;

        var envInfoTable = $this.find('.env-info-table');
        if (window.resPar) {
            //编辑管理CPU个数或者线程数
            var cni = envInfoTable.find('input[name=manage-cpu-num-input]');
            if (cni.length == 1) cni.addClass("ui-state-disabled");
            //编辑管理内存或者内存
            var mmi = envInfoTable.find('input[name=manage-memory-input]');
            if (mmi.length == 1) mmi.addClass("ui-state-disabled");
            //编辑执行器个数
            var eni = envInfoTable.find('input[name=executor-num-input]');
            if (eni.length == 1) eni.addClass("ui-state-disabled");
            //编辑运行内存个数
            var rcni = envInfoTable.find('input[name=run-cpu-num-input]');
            if (rcni.length == 1) rcni.addClass("ui-state-disabled");
            //编辑运行内存
            var rmi = envInfoTable.find('input[name=run-memory-input]');
            if (rmi.length == 1) rmi.addClass("ui-state-disabled");
            //编辑缓存设置
            var ccs = envInfoTable.find('select[name=cache-config-select]');
            if (ccs.length == 1) ccs.selectmenu("option", "disabled", true);
            //编辑执行环境
            var ms = envInfoTable.find('select[name=mode-select]');
            if (ms.length == 1) ms.selectmenu("option", "disabled", true);
            //编辑gpu
            var gpu = envInfoTable.find('input[name=gpu]');
            if (gpu.length == 1) gpu.addClass("ui-state-disabled");
        }
    };

    /**
     * 初始化环境参数
     * @returns {boolean}
     */
    var initEnvParamsInfoPage = function () {
        if (!getEnvParamsHtml()) {
            return false;
        }
        scrollChange();
    };

    /**
     * 初始化环境参数
     */
    var initEnvParamsInfo = function () {
        initEnvParamsInfoPage();
    };

    /**
     * 初始化资源管理
     */
    var initResourceInfo = function () {
        Eventbus.trigger("initResourceMonitor.mine", $resource, resourceGrid);
    };

    /**
     * 初始化流程参数
     */
    var initFlowParamInfoPage = function () {
        paramGrid.datagrid({
            datatype: "local",
            data: flowArray,
            pagination: false,
            rowNum: 100000,
            striped: true,
            shrinkToFit: true,
            fit: true,
            colNames: ["参数名称", "参数值", "参数说明", "参数类型", "节点类型", "ID", "原先参数值"],
            colModel: [{
                name: 'paramName',
                index: 'paramName',
                sortable: false
            }, {
                name: 'paramValue',
                index: 'paramValue',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    var cellvalueFormated = cellvalue;
                    if (rowObject.paramType && rowObject.paramType === "datasource") {
                        $.ajax({
                            url: contextPath + '/api/ai/node/io/get-datasource-by-code',
                            type: 'post',
                            async: false,
                            data: {
                                code: JSON.stringify([cellvalue])
                            },
                            success: function (data) {
                                try {
                                    cellvalue = data.data[0].name;
                                } catch (e) {
                                    console.log(data);
                                }
                            }
                        });
                        cellvalueFormated = cellvalue;
                    } else {
                        cellvalueFormated = cellvalue;
                    }
                    return valueFormater(cellvalueFormated)
                }
            }, {
                name: 'paramDesc',
                index: 'paramDesc',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    if (cellvalue) {
                        return cellvalue;
                    } else {
                        return "";
                    }
                }
            }, {
                name: "paramType",
                index: "paramType",
                hidden: true
            }, {
                name: "nodeType",
                index: "nodeType",
                hidden: true
            }, {
                name: "paramId",
                index: "paramId",
                hidden: true
            }, {
                name: 'paramValue',
                index: 'paramValue',
                hidden: true
            }],
            onSelectRow: function (rowId, status, event) {
                $(event.target).parent().removeClass("ui-state-highlight");
            }
        });
        $paramInfo.find(".ui-jqgrid-resize-ltr").css("display", "none");
        paramGrid.parent().parent().css("height", paramGrid[0].offsetHeight);
        scrollChange();
    };

    /**
     *  将 input 框中的括号进行替换
     * */
    var valueFormater = function (value) {
        if (value == null) {
            return "";
        } else {
            value = typeof value == "string" ? value.replace("<", "&lt;").replace(">", "&gt;") : value;
            return value;
        }
    };

    /**
     * 流程参数页面数据保存后回调
     */
    var flowParamInitSave = function () {

        for (var i = 1; i <= flowArray.length; i++) {
            var paramValueTd = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(2)");
            var paramValue = paramValueTd.find("select").selectmenu("getValue");

            var paramType = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(4)").text();
            if (paramType && paramType === "datasource") {
                $.ajax({
                    url: contextPath + '/api/ai/node/io/get-datasource-by-code',
                    type: 'post',
                    async: false,
                    data: {
                        code: JSON.stringify([paramValue])
                    },
                    success: function (data) {
                        paramValueTd.empty().text(data.data[0].name);
                    }
                });
            } else {
                paramValueTd.empty().text(paramValue);
            }
        }
        flowArray = window.resPar.filter(function (v) {
            if (v === null) {
                return false;
            }
            if (v.paramName === "system.appId") {
                return false;
            } else if (v.$configResources$ == null) {
                return true;
            }
        });
    };

    /**
     * 编辑流程参数表格
     */
    var editFlowParamsTable = function () {
        var trs = paramGrid.find("tr");
        for (var i = 1; i < trs.length; i++) {
            var paramValueTd = $(trs[i]).find("td:nth-child(2)");
            var paramValue = paramValueTd.text();
            paramValueTd.empty();

            var paramValueSelect = $('<select />').val(paramValue).appendTo(paramValueTd);
            var pss = [];

            var paramTypeTd = $(trs[i]).find("td:nth-child(4)");
            var type = paramTypeTd.text();

            var nodeTypeTd = $(trs[i]).find("td:nth-child(5)");
            var nodeType = nodeTypeTd.text();

            if (type == 'datasource') {
                var loadDatasource = function (data) {
                    for (var j = 0; j < data.length; j++) {
                        var dataItem = data[j];
                        // 屏蔽模型数据源、presto数据源、impala数据源
                        if (nodeType == 'readrdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
                                continue;
                            }
                        }
                        if (nodeType == 'writerdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }

                        if (nodeType == 'readhive') {
                            if (dataItem.type != 'hive') {
                                continue;
                            }
                        }
                        if(nodeType == 'writehive'){
                            if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
                                continue;
                            }
                        }
                        if (nodeType == "readinfluxdb") {
                            if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
                                continue;
                            }
                        }
                        if( nodeType == "readiotdb"){
                            if (dataItem.type != 'iotdb') {
                                continue;
                            }
                        }
                        if( nodeType == "writeiotdb"){
                            //不是iotdb  或者不能写入
                            if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }
                        if (nodeType == "readtaosdb") {
                            if (dataItem.type != "taosDB") {
                                continue;
                            }
                        }

                        pss.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
                    }
                    var html = pss.join('');
                    paramValueSelect.html(html);

                    paramValueSelect.selectmenu({
                        editable: false,
                        width: '80%',
                    }).selectmenu('setValue', $(trs[i]).find("td:nth-child(7)").text()).selectmenu('refresh');
                };
                if (dataSourceCache['datasource']) {
                    loadDatasource(dataSourceCache['datasource']);
                } else {
                    $.ajax({
                        url: contextPath + '/api/ai/node/io/list-datasources',
                        type: 'post',
                        async: false,
                        success: function (data) {
                            if (data.success) {
                                dataSourceCache['datasource'] = data.data;
                                loadDatasource(dataSourceCache['datasource']);
                            } else {
                                console.error("数据源加载失败");
                            }
                        }
                    });
                }
            } else {
                var items = TempoMineUtils.getConstFlowParams();
                if (items) {
                    for (name in items) {
                        pss.push('<option value="' + name + '">' + items[name] + '</option>')
                    }
                }

                var html = pss.join('');
                paramValueSelect.html(html);
                paramValueSelect.selectmenu({
                    editable: true,
                    width: '80%',
                }).selectmenu('setValue', paramValue);
            }
        }
    }

    /**
     * 初始化Python资源设置
     * 只有在异步服务会有
     */
    var initLimitInfoPage = function () {
        $.ajax({
            url: contextPath + "/api/ai/mine/getClusterParams",
            type: 'post',
            success: function (response) {
                var result = response.data;
                //判断系统管理是否开启python资源限制
                var isOpen = result.resourceLimitEnable;
                if (!isOpen) {
                    $limitInfo.remove();
                    $this.find(".app-task-config-container-right").find('a[navTo="#limit-info"]').parent().remove();
                } else {
                    //获取python资源限制默认参数值
                    var pythonLimitParam = ajaxLoadingPythonLimit();
                    //CPU个数输入框初始化
                    var extendCpuTd = limitGrid.find("td[name=limitExtendCpu]");
                    extendCpuTd.empty();
                    var extendCpuInput = $('<input name="limitExtendCpuInput" />').val(pythonLimitParam.limitExtendCpu).appendTo(extendCpuTd);
                    extendCpuInput.numberbox({
                        range: '[1, 16]',
                        validator: true,
                        required: true,
                        autofill: false,
                        precision: 0,
                    }).addClass("ui-state-disabled");
                    //内存（GB）输入框初始化
                    var extendMemoryTd = limitGrid.find("td[name=limitExtendMemory]");
                    extendMemoryTd.empty();
                    var extendMemoryInput = $('<input name="limitExtendMemoryInput" />').val(pythonLimitParam.limitExtendMemory).appendTo(extendMemoryTd);
                    extendMemoryInput.numberbox({
                        range: '[1, 32]',
                        validator: true,
                        required: true,
                        autofill: false,
                        precision: 0,
                    }).addClass("ui-state-disabled");
                    var configResources = resPar.filter(function (v) {
                        if (v.$configResources$ != null) {
                            return true;
                        }
                    });
                    if (configResources.length > 0) {
                        var json = JSON.parse(configResources[0]["$configResources$"]);
                        extendCpuInput.val(json.limitCpu || pythonLimitParam.limitExtendCpu);
                        extendMemoryInput.val(json.limitMemory || pythonLimitParam.limitExtendMemory);
                    } else {
                        console.error("initLimitInfo", "the parseing of $configResources$ is error");
                    }
                }
                scrollChange();
            }
        });
    };

    /**
     * 流程参数页面数据保存后回调
     */
    var limitInitSave = function () {
        var extendCpuInput = limitGrid.find("input[name=limitExtendCpuInput]");
        //设置CPU个数取消编辑
        extendCpuInput.addClass("ui-state-disabled");

        var extendMemoryInput = limitGrid.find("input[name=limitExtendMemoryInput]");
        //设置内存(GB)取消编辑
        extendMemoryInput.addClass("ui-state-disabled");
    };

    /**
     * 回填资源限制表格的方法
     * @returns {{limitExtendMemory: *, limitExtendCpu: *}}
     */
    var ajaxLoadingPythonLimit = function () {
        var limitExtendCpu = 2;
        var limitExtendMemory = 2;
        $.ajax({
            url: contextPath + "/api/ai/mine/getClusterParams",
            type: 'post',
            async: false,
            success: function (response) {
                var result = response.data;
                limitExtendCpu = result.limitExtendCpu;
                limitExtendMemory = result.limitExtendMemory;
            }
        });
        return {
            "limitExtendCpu": limitExtendCpu,
            "limitExtendMemory": limitExtendMemory
        };
    };

    /**
     * 编辑Python资源限制表table
     */
    var editPythonLimitTable = function () {
        //CPU个数
        var extendCpuInput = limitGrid.find("input[name=limitExtendCpuInput]");
        //内存(GB)
        var extendMemoryInput = limitGrid.find("input[name=limitExtendMemoryInput]");
        //CPU个数编辑
        extendCpuInput.removeClass("ui-state-disabled");
        //内存(GB)编辑
        extendMemoryInput.removeClass("ui-state-disabled");
    }

    /**
     * 保存Python资源限制表table
     */
    var savePythonLimitTable = function () {
        editStatus.limit = false;
        //保存python 资源限制事件
        var extendCpuInput = limitGrid.find("input[name=limitExtendCpuInput]");
        var extendMemoryInput = limitGrid.find("input[name=limitExtendMemoryInput]");

        var flowParams = resPar.filter(function (v) {
            if (v.paramName != "system.appId") {
                if (v.$configResources$ != null) {
                    var parse = JSON.parse(v.$configResources$);
                    parse.limitCpu = extendCpuInput.val();
                    parse.limitMemory = extendMemoryInput.val();
                    v.$configResources$ = JSON.stringify(parse);
                    return true;
                }
                return true;
            }
        });
        window.resPar = flowParams;
        limitInitSave();
    }

    /**
     * 初始化流程参数
     */
    var initFlowParamInfo = function () {
        initFlowParamInfoPage();
    };

    /**
     * 初始化Python资源限制
     */
    var initLimitInfo = function () {
        initLimitInfoPage();
    };

    /**
     * 监听滚动条移动的位置
     * 1、获取到每一个DIV距离top的高度，
     * 2、计算滚动条的高度，进行比对得出下标
     * 3、点亮右边的按钮
     */
    var scrollChange = function () {
        var $left = $this.find(".app-task-config-container-left");
        /**
         * 获取所有模块的数组
         */
        var getHeight = function () {
            var $blocks = $left.find("div[sign=block]");
            var len = $blocks.length;
            var data = [];
            for (var i = 0; i < len; i++) {
                var h = $blocks[i].clientHeight;
                if (i == 0) {
                    data[i] = h;
                } else {
                    data[i] = data[i - 1] + h;
                }
            }
            return data;
        };

        var arrHeight = getHeight();

        var getIndex = function (top) {
            for (var i = 0; i < arrHeight.length; i++) {
                if (top < arrHeight[i]) {
                    return i;
                }
            }
        };
        $left.parent().unbind("scroll").bind("scroll", function () {
            var dialog = $this.find(".tempo-mine-flow-job-container");
            dialog.find('[name="starttime"]').datepicker('hide');
            dialog.find('[name="starttime"]').blur();
            dialog.find('[name="endtime"]').datepicker('hide');
            dialog.find('[name="endtime"]').blur();

            dialog.find('.timefield').timepicker('hide');
            dialog.find('.timefield').blur();

            var $ul = $this.find(".app-task-config-container-right").find("ul");
            var $liList = $ul.children();
            var len = $liList.length;
            var lis = [];
            for (var i = 0; i < len; i++) {
                if ($liList[i].tagName.toUpperCase() == "LI") {
                    lis.push($liList[i]);
                }
            }
            //根据滚动事件，计算当前应该是哪个模块被激活
            var top = this.scrollTop;
            var index = getIndex(top);
            var liLength = lis.length;
            for (var i = 0; i < liLength; i++) {
                var cls = $(lis[i]).find("a")[0].className;
                if (cls && i != index) {
                    $(lis[i]).find("a").removeClass("light");
                }
                if (i == index) {
                    $(lis[i]).find("a").addClass("light");
                }
            }
        });
    };

    /**
     * 初始化右边列表点击事件，锚点连接
     */
    var initLIInfo = function () {
        var $ul = $this.find(".app-task-config-container-right").find("ul");
        $ul.find("a.navItems").unbind("click").bind("click", function (e) {
            var navTo = $(this).attr('navTo');
            var $div = $(navTo);
            var top = $div[0].offsetTop || 0;
            $('.app-task-config-container-body').animate({
                'scroll-top': top
            }, 500);
        });
    };

    var initTaskForm = function () {
        var operHtml = buildOperHtml();
        $(operHtml).appendTo($this.find(".tempo-task-configuration-operation"));
        initFormData($this.find(".tempo-mine-flow-job-container"), job);
        setFlowParams($this.find(".tempo-mine-flow-job-container"), job);
        //初始化环境参数
        initEnvParamsInfo();
        //初始化资源管理
        initResourceInfo();
        //初始化流程参数
        initFlowParamInfo();
        //初始化Python资源限制
        initLimitInfo();
        //绑定页面事件
        bindEvent(job);
        //初始化页面组件禁用
        configInitDisabled(job);
        //刷新调度按钮状态
        refreshStopOrManualStatus(job);
        setTimeout(scrollChange(), 1000);
        //初始化右边列表点击事件，锚点连接
        initLIInfo();

        //如果调度服务不可用，不准操作
        $.post(contextPath + '/api/ai/app/schedule/group', function (response) {
            if (!response.success) {
                $("#tempo-task-stop" + id)
                    .addClass("tempo-api-icon-18-position-task-stop-disabled")
                    .addClass("tempo-task-button-disabled");
                $("#tempo-task-stop" + id + " span")
                    .addClass("tempo-task-label-disabled");
                $("#tempo-task-pause" + id)
                    .addClass("tempo-api-icon-18-position-task-stop-disabled")
                    .addClass("tempo-task-button-disabled");
                $("#tempo-task-pause" + id + " span")
                    .addClass("tempo-task-label-disabled");
                $("#tempo-task-manual" + id)
                    .addClass("tempo-api-icon-18-position-task-manual-disabled")
                    .addClass("tempo-task-button-disabled");
                $("#tempo-task-manual-label" + id).addClass("tempo-task-label-disabled");
                $this.find("#tempo-task--param-save" + id).button('disable');
                $("<div/>").alert({msg: TempoUtils.locale("mine.schedule_service_unavilable"), height: 180});
            }
        });
    }
    $.ajax({
        url: contextPath + '/api/ai/mine/publish/listJobInfo',
        type: 'post',
        dataType: 'json',
        data: {
            id: args.id
        },
        success: function (result) {
            if ("true" == result.flag) {
                job = result.job;
                firstJobStatus = result.job.trigger.status;
                initTaskForm();
            } else {
                initTaskForm({});
            }
        }
    });
});